import { getMenus } from "@/api/index.js";
import router from "@/router";
const user = {
  state: {
    token: JSON.parse(sessionStorage.getItem("userInfo"))?.token || "",
    userInfo: JSON.parse(sessionStorage.getItem("userInfo"))?.userInfo || "",
    menuList: [], //获取到的路由,无需获取本地数据,丢失直接beforeEach重新获取
    btnList: [], //按钮权限
  },

  mutations: {
    SET_ROUTES: (state, routes) => {
      state.menuList = routes;
    },
    SET_USERINFO: (state, userInfo) => {
      state.token = userInfo.token;
      console.log("userInfo", state.token);
      state.userInfo = userInfo.userInfo;
      state.btnList = userInfo.btnPermission;
    },
  },

  actions: {
    //获取菜单
    getMenuList({ state, commit }, role) {
      return new Promise((resolve) => {
        getMenus(role).then((res) => {
          if (res.code === 200) {
            commit("SET_ROUTES", res.data);
            sessionStorage.setItem("menuList", JSON.stringify(res.data));
            resolve(state.menuList);
          }
        });
      });
    },
    // 登出
    LogOut({ commit }) {
      router.replace("/login");
      sessionStorage.clear();
      location.reload();
    },
  },
};

export default user;
